/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ar.edu.utn.frsf.ofa.javaee7.tp.ejemplo.ecompras.controller;


import ar.edu.utn.frsf.ofa.javaee7.tp.ejemplo.ecompras.modelo.Obra;
import ar.edu.utn.frsf.ofa.javaee7.tp.ejemplo.ecompras.util.BaseProduccion;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;

/**
 *
 * @author Administrador
 */
@Named(value = "obraController")
@SessionScoped
public class ObraController implements Serializable {

    @Inject
    @BaseProduccion
    EntityManager em;
    
    @Inject
    transient Logger miLogger;
    
    private Obra obra;

    private List<Obra> listaObras;

    @PostConstruct
    public void init(){
        miLogger.log(Level.INFO," INICIO BEAN INSUMO CONTROLLER ");
    }
    
    @Transactional
    private List<Obra> buscarTodos(){
        return em.createQuery("SELECT o FROM Obra o").getResultList();
    }


    private void insertarGuardar(){
        if(this.obra.getId()<=0 ) {
            em.persist(this.obra);
            em.flush();
            em.refresh(this.obra);
        }
        else {
            this.obra= em.merge(this.obra);
        }        
    }
    
    public String editar(){
        return null;
    }
    public String nuevo(){
        miLogger.log(Level.INFO," CREAR NUEVO INSUMO");
        this.obra = new Obra();
        return null;
    }

   @Transactional
     public String guardar(){
        this.insertarGuardar();
        this.listaObras = this.buscarTodos();
        this.obra = null;
        return null;
    }

   @Transactional
     public String borrar(){
        this.em.remove(this.obra);
        this.listaObras = this.buscarTodos();
        this.obra = null;
        return null;
    }

    public String cancelar(){
        this.obra = null;
        return null;
    }
    /**
     * @return the obra
     */
    public Obra getObra() {
        return obra;
    }

    /**
     * @param obra the obra to set
     */
    public void setObra(Obra obra) {
        this.obra = obra;
    }

    /**
     * @return the listaObras
     */
    public List<Obra> getListaObras() {
         if (this.listaObras == null) {
            this.listaObras = em.createQuery("SELECT o FROM Obra o").getResultList();
        }
        return listaObras;
    }

    /**
     * @param listaObras the listaObras to set
     */
    public void setListaObras(List<Obra> listaObras) {
        this.listaObras = listaObras;
    }

}
